<template>
  <a-modal
    v-model:visible="addVisable"
    :title="typeEnum[title]"
    :width="650"
    title-align="start"
    ok-text="保存"
    @cancel="closeAddDialog"
    @before-ok="handleSubmit"
    modal-class="formModal"
    :mask-closable="false"
  >
    <a-form ref="ruleFormRef" :model="ruleForm" style="max-height: 500px" :disabled="disabled">
      <a-spin>
        <a-row>
          <a-col :span="12">
            <a-form-item
              field="metricsName"
              label="指标名称"
              label-col-flex="110px"
              :rules="[{ required: true, message: '请输入指标名称' }]"
            >
              <a-input v-model="ruleForm.metricsName" placeholder="请输入指标名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="metricsCode"
              label="指标代号"
              label-col-flex="110px"
              :rules="[{ required: true, message: '请输入指标代号' }]"
            >
              <a-input v-model="ruleForm.metricsCode" placeholder="请输入指标代号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item field="paramCode" label="选择数据" label-col-flex="110px">
              <a-select v-model="ruleForm.paramCode" placeholder="请选择参数">
                <a-option :value="item.dataCode" v-for="item in props.newParamsList" :key="item.dataCode">{{
                  item.dataName
                }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <!--<a-row v-if="isRelevance">
          <a-col :span="12">
            <a-form-item field="paramNodeId" label="节点名称" label-col-flex="110px">
              <a-select v-model="ruleForm.paramNodeId" placeholder="请选择节点" @change="getParamList" allow-search>
                <a-option v-for="item in nodeList" :key="item.id" :value="item.id">{{ item.nodeName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="type"
              label="关联参数类型"
              label-col-flex="110px"
              :rules="[{ required: true, message: '请选择关联参数类型' }]"
            >
              <a-select v-model="ruleForm.type" placeholder="请选择关联参数类型" @change="getParamList" allow-search>
                <a-option :value="1">遥测参数</a-option>
                <a-option :value="2">功能指标</a-option>
                <a-option :value="3">性能指标</a-option>
                <a-option :value="4">健康度</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="isRelevance">
          <a-col :span="12">
            <a-form-item field="paramName" label="关联参数名称" label-col-flex="110px">
              <a-select
                v-model="ruleForm.paramName"
                placeholder="请选择关联参数名称"
                @change="changeParamName"
                allow-search
              >
                <a-option v-for="item in paramNameList" :value="item.paramName" :key="item.id"
                  >{{ item.paramName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="paramCode" label="关联参数code" label-col-flex="110px">
              <a-input v-model="ruleForm.paramCode" placeholder="请选择关联参数code" :disabled="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="notes" label="说明" v-if="isHealth">
          <a-textarea v-model="ruleForm.notes" placeholder="请输入说明" auto-size allow-clear />
        </a-form-item>
        <a-form-item field="functionIds" label="功能参数集" v-if="!isHealth && !isRelevance">
          <a-transfer :data="functionList" :default-value="ruleForm.functionIds" v-model="ruleForm.functionIds">
            <template #source-title="{ checked, indeterminate, onSelectAllChange }">
              <div :style="styleHeader">
                已配置参数
                <a-checkbox :model-value="checked" :indeterminate="indeterminate" @change="onSelectAllChange" />
              </div>
            </template>

            <template #target-title="{ onClear }">
              <div :style="styleHeader">
                已选择参数
                <IconDelete @click="onClear" />
              </div>
            </template>
          </a-transfer>
        </a-form-item>
        <a-form-item field="performanceIds" label="性能参数集" v-if="!isHealth && !isRelevance">
          <a-transfer
            :data="performanceList"
            :default-value="ruleForm.performanceIds"
            v-model="ruleForm.performanceIds"
          >
            <template #source-title="{ checked, indeterminate, onSelectAllChange }">
              <div :style="styleHeader">
                已配置参数
                <a-checkbox :model-value="checked" :indeterminate="indeterminate" @change="onSelectAllChange" />
              </div>
            </template>

            <template #target-title="{ onClear }">
              <div :style="styleHeader">
                已选择参数
                <IconDelete @click="onClear" />
              </div>
            </template>
          </a-transfer>
        </a-form-item>
        <a-form-item field="paramIds" label="计算参数集" v-if="!isRelevance && isHealth">
          <a-transfer :data="paramsList" :default-value="ruleForm.paramIds" v-model="ruleForm.paramIds">
            <template #source-title="{ checked, indeterminate, onSelectAllChange }">
              <div :style="styleHeader">
                已配置参数
                <a-checkbox :model-value="checked" :indeterminate="indeterminate" @change="onSelectAllChange" />
              </div>
            </template>

            <template #target-title="{ onClear }">
              <div :style="styleHeader">
                已选择参数
                <IconDelete @click="onClear" />
              </div>
            </template>
          </a-transfer>
          &lt;!&ndash; <div>
          <a-table :columns="columns" :data="data" :scroll="scroll" :row-selection="rowSelection" :bordered="false" :pagination="false" :sticky-header="100"/>
        </div> &ndash;&gt;
        </a-form-item>-->
        <a-form-item field="customParam" label="自定义" :rules="[{ required: true, message: '请输入脚本内容' }]">
          <codemirror
            :disabled="disabled"
            class="codemirror"
            v-model="ruleForm.customParam"
            placeholder=""
            :lineNumbers="true"
            :style="{ height: '300px', width: '100%' }"
            :autofocus="true"
            :tabSize="2"
            :extensions="extensions"
          />
        </a-form-item>
        <!--<a-form-item field="script" label="脚本说明">
          <a-button type="primary" style="background-color: #3075ac" @click="funDownloadScript">点击下载</a-button>
        </a-form-item>-->
      </a-spin>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, toRefs, defineProps, defineExpose, computed } from 'vue'
import { apiHome } from '@/api/healthAssessment'
import { Codemirror } from 'vue-codemirror'
import axios from 'axios'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'
import { Message } from '@arco-design/web-vue'
import { IconDelete } from '@arco-design/web-vue/es/icon'

const extensions = ref([javascript(), oneDark])
const props = defineProps({
  title: {
    type: String,
    default: 'HEALTH'
  },
  nodeList: {
    type: Array,
    default: () => []
  },
  // 计算参数集
  paramsList: {
    type: Array,
    default: () => []
  },
  // 性能集
  performanceList: {
    type: Array,
    default: () => []
  },
  // 功能集
  functionList: {
    type: Array,
    default: () => []
  },
  // 参数集
  newParamsList: {
    type: Array,
    default: () => []
  },
  funNodesInfoShow: {
    type: Function,
    required: true
  }
})
const styleHeader = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  paddingRight: '8px'
}
const disabled = ref(false)
const { title, nodeList, paramsList, performanceList, functionList } = toRefs(props)
const isHealth = computed(() => {
  return title.value !== 'HEALTH'
})
const isRelevance = computed(() => {
  return title.value === 'PARAM'
})
const addVisable = ref(false)
const ruleFormRef = ref(null)
const formType = ref('')
const nodeIds = ref('')
const paramNameList = ref([])
const ruleForm = ref({
  id: '',
  customParam: 'function(){}', // 自定义
  metricsName: '', // 指标名称
  metricsCode: '', // 指标代号
  paramCode: '', // 节点代号
  paramName: '', // 节点参数
  notes: '', // 说明
  type: '', // 关联参数类型
  paramIds: [], // 计算参数集
  nodeId: '', // 节点id
  functionIds: [],
  performanceIds: []
})
// 查询接口
const getDetailEnum = reactive({
  PARAM: apiHome.getAssociationParameterDetail,
  HEALTH: apiHome.getHealthDeep,
  FUNCTIONAL: apiHome.getFunctionalInfo,
  PERFORMANCE: apiHome.getPerformanceInfo
})
// 提交接口
const submitEnum = reactive({
  PARAM: apiHome.saveAssociationParameter,
  HEALTH: apiHome.saveHealthDeep,
  FUNCTIONAL: apiHome.saveFunctionalIndicators,
  PERFORMANCE: apiHome.savePerformanceIndicators
})
const editEnum = reactive({
  PARAM: apiHome.updateAssociationParameter,
  HEALTH: apiHome.updateHealthDeep,
  FUNCTIONAL: apiHome.updateFunctionalIndicators,
  PERFORMANCE: apiHome.updatePerformanceIndicators
})
const openAddDialog = (data, type, nodeIdParam) => {
  ruleForm.value = {
    id: '',
    paramNodeId: '',
    customParam: 'function(){}',
    metricsName: '',
    metricsCode: '',
    paramCode: '',
    paramName: '',
    notes: '',
    type: '',
    paramIds: [],
    nodeId: '',
    functionIds: [],
    performanceIds: []
  }
  disabled.value = false
  if (type === 1 || type === 2) {
    getDetailEnum[title.value](data).then((res) => {
      if (+res.code === 200) {
        ruleForm.value.type = res.data.type
        ruleForm.value.paramNodeId = res.data.paramNodeId
        if (type === 2) {
          getParamList()
        }
        ruleForm.value = {
          ...res.data
        }
      } else {
        Message.error(res.message)
      }
    })
  } else if (type === 4) {
    getDetailEnum.HEALTH(nodeIdParam).then((res) => {
      if (+res.code === 200) {
        ruleForm.value = {
          ...res.data
        }
      } else {
        Message.error(res.message)
      }
    })
  }
  if (type === 1) disabled.value = true
  formType.value = type
  nodeIds.value = nodeIdParam
  ruleFormRef.value.resetFields()
  addVisable.value = true
}
const closeAddDialog = () => {
  addVisable.value = false
  disabled.value = false
}
const typeEnum = reactive({
  PARAM: '关联参数设置',
  HEALTH: '健康度设置',
  FUNCTIONAL: '功能指标设置',
  PERFORMANCE: '性能指标设置'
})
const handleSubmit = (done) => {
  ruleFormRef.value.validate((errors) => {
    if (!errors) {
      const customParam = ruleForm.value.customParam.replace(/\s+/g, '')
      if (customParam.length <= 12) {
        Message.error('请填写脚本内容')
        return
      }
      ruleForm.value.nodeId = nodeIds.value
      if (+formType.value === 2 || ruleForm.value.id) {
        editEnum[title.value](ruleForm.value)
          .then((res) => {
            if (+res.code === 200) {
              Message.success('编辑成功')
              addVisable.value = false
              props.funNodesInfoShow(nodeIds.value, title.value, 1)
            } else {
              Message.error(res.message)
            }
            done(false)
          })
          .catch(() => {
            done(false)
          })
      } else if (+formType.value === 1) {
        closeAddDialog()
      } else {
        submitEnum[title.value](ruleForm.value)
          .then((res) => {
            if (+res.code === 200) {
              Message.success('新增成功')
              addVisable.value = false
              props.funNodesInfoShow(nodeIds.value, title.value, 1)
            } else {
              Message.error(res.message)
            }
            done(false)
          })
          .catch(() => {
            done(false)
          })
      }
    }
  })
  done(false)
}
const getParamList = () => {
  ruleForm.value.paramName = ''
  ruleForm.value?.type &&
    ruleForm.value?.paramNodeId &&
    apiHome.getParamList(ruleForm.value.type, ruleForm.value.paramNodeId).then((res) => {
      if (+res.code === 200) {
        paramNameList.value = res.data
      } else {
        Message.error(res.message)
      }
    })
}
const changeParamName = (val) => {
  ruleForm.value.paramCode = paramNameList.value.filter((item) => {
    return item.paramName === val
  })[0].paramCode
}
// 下载脚本
const funDownloadScript = () => {
  axios(`${import.meta.env.VITE_APP_BASE_ASSETS}docs/scriptTemplate.docx`, {
    responseType: 'blob' // 重要代码
  }).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    const fileName = '脚本说明.docx' // 保存到本地的文件名称
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
  })
}
defineExpose({
  openAddDialog,
  closeAddDialog
})
</script>

<style lang="less" scoped>
.codemirror {
  text-align: start;
}
</style>
